using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UMC.Data;
using UMC.Web;
using UMC.Web.UI;

using UMC.WorkFlow.Entities;

namespace UMC.WorkFlow
{


    [Apiumc("WorkFlow", "Control", Auth = WebAuthType.Admin, Desc = "表单设计")]
    public class WorkFlowFormControlActivity : WebActivity
    {
        void Check(TaskForm taskForm)
        {
            if (String.IsNullOrEmpty(taskForm.ProviderKey))
            {
                this.Prompt("请先设置表单的数据库节点");
            }
        }
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var SId = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("Id", g =>
            {
                var grid = new TaskFormGridDialog() { Title = "表单列表" };

                return grid;
            })) ?? 0;

            var taskForm = DataFactory.Instance().TaskForm(SId);
            if (taskForm == null)
            {
                this.Prompt("无此流程设计");
            }
            else
            {
                SId = taskForm.TaskId.Value;
            }


            var vform = Utility.UInt64Parse(this.AsyncDialog("Item", g =>
            {
                var controls = DataFactory.Instance().TaskFormControl(taskForm.TaskId.Value, 0);// entity.Query();
                var ui = UISection.Create(new UITitle("表单设计"));
                ui.UIFootBar = new UIFootBar()
                .AddText(new UIEventText("可视设置").Click(
                         new UIClick(request.Model, "CheckControl", new UMC.Web.WebMeta().Put("Id", "Default").Put("Task", SId))))

                .AddText(new UIEventText("添加新项")
                    .Click(new UIClick(request,g, "0")).Style(new UIStyle().BgColor()));
                ui.UIFootBar.IsFixed = true;
                var ucl = ui;
                foreach (var cl in controls)
                {
                    if (String.IsNullOrEmpty(cl.Tip) == false && cl.Type != ControlType.List)
                    {
                        ucl = ui.NewSection();
                        ucl.Header.Put("text", cl.Tip);
                    }

                    switch (cl.Type ?? ControlType.Text)
                    {
                        case ControlType.List:

                            ucl = ui.NewSection();

                            ucl.AddCell('\uF022', cl.Caption, "配置列表项"
                                , new UIClick(request,g, cl.ItemId.ToString()));

                            ucl = ui.NewSection();
                            break;
                        default:
                            ucl.AddCell(cl.Caption, cl.PlaceHolder ?? cl.Caption
                                , new UIClick(request, g, cl.ItemId.ToString()));
                            break;
                    }

                }
                ui.SendTo(this.Context, "WorkFlow.Control");
            })).Value;
            if (vform == 0)
            {
                var forId = Utility.UInt64Parse(this.AsyncDialog("ForId", g =>
               {
                   return this.DialogValue("0");
               })).Value;
                var vform2 = this.AsyncDialog("ItemConfig", g =>
                {
                    var vf = new UIFormDialog() { Title = "添加组件" };
                    vf.AddText("组件代码", "Code");
                    vf.AddText("组件标题", "Caption");

                    var opts = vf.AddRadio("类型", "Type").Put("只读", ControlType.Readonly.ToString())
                         .Put("文本", ControlType.Text.ToString()).Put("日期", ControlType.Date.ToString())
                         .Put("选择框", ControlType.Select.ToString());
                    if (forId == 0)
                    {
                        opts.Put("列表", ControlType.List.ToString());
                    }
                    opts.Put("数字", ControlType.Number.ToString()).Put("扫一扫", ControlType.Scaning.ToString());
                    vf.Submit("确认添加", "WorkFlow.Control");
                    return vf;
                });
                var cf = new TaskFormControl();
                UMC.Data.Reflection.SetProperty(cf, vform2.GetDictionary());
                cf.ItemId = Utility.NewId();
                cf.ForId = forId;// Guid.Empty;
                cf.TaskId = SId;

                var controls2 = DataFactory.Instance().TaskFormControl(SId, forId);//.Any(r=>r.Code==cf.Code);

                if (controls2.Any(r => r.Code == cf.Code))
                {
                    this.Prompt("已经存在此代码");
                }
                else
                {
                    cf.Seq = (controls2.MaxBy(r => r.Seq ?? 0)?.Seq ?? 0) + 1;

                    DataFactory.Instance().Put(cf);
                }
            }
            else
            {
                var sub = HotCache.Get(new TaskFormControl { ItemId = vform });//.Entities.Single();
                var Model = this.AsyncDialog("Model", g =>
               {


                   var ui = UISection.Create(new UITitle("组件设计"));
                   ui.AddCell("代码", sub.Code
                       , new UIClick(request,g, "Code"));

                   if (sub.Type == ControlType.List)
                   {
                       ui.Title.Title = "列表组件设计";
                       ui.AddCell("类型", sub.Type.ToString());
                   }
                   else
                   {
                       ui.AddCell("类型", sub.Type.ToString(), new UIClick(request,g, "Type"));
                   }
                   var baseUI = ui.NewSection().AddCell("标题", sub.Caption
                            , new UIClick(request,g, "Caption"))
                        .AddCell("空值提示", sub.PlaceHolder
                            , new UIClick(request,g, "PlaceHolder"))

                        .AddCell("必须输入", sub.IsRequired == true ? "是" : "否"
                            , new UIClick(request,g, "IsRequired"))
                        .AddCell("展示顺序", sub.Seq.ToString()
                            , new UIClick(request,  g, "Seq"));
                   switch (sub.Type)
                   {
                       case ControlType.List:

                           baseUI
                            .AddCell("值字段", sub.ValueKey
                                , new UIClick(request, g, "ValueKey"));

                           var controls = DataFactory.Instance().TaskFormControl(SId, sub.ItemId.Value);
                           var ucl = baseUI.NewSection();
                           ucl.Header.Put("text", "列表字段");

                           foreach (var cl in controls)
                           {

                               ucl.AddCell(cl.Caption, cl.Code
                                   , new UIClick(request.Model, request.Command, new WebMeta().Put("Id", SId).Put("Item", cl.ItemId)));
                           }
                           var desc = new UMC.Web.UI.UIDesc(new UMC.Web.WebMeta().Put("desc", "增加列表项").Put("icon", "\uF055"));
                           desc.Desc("{icon} {desc}");
                           desc.Click(new UIClick(request.Model, request.Command, new WebMeta().Put("Id", SId).Put("Item", 0).Put("ForId", sub.ItemId)));
                           desc.Style.Align(1).Color(0xaaa).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(18));



                           ucl.Add(desc);

                           break;
                       default:
                           if ((sub.ForId ?? 0) == 0)
                           {
                               baseUI.AddCell("组名", sub.Tip
                                   , new UIClick(request,g, "Tip"));
                           }
                           break;
                   }
                   var ui2 = ui.NewSection();

                   ui2.AddCell("值处理脚本", "单行加入"
                                , new UIClick(request,g, "ValueSQL"));
                   ui2.AddCell("值效验脚本", "文本提示"
                                , new UIClick(request,g, "CheckSQL"));
                   ui2.AddCell("空值效验脚本", "大于零"
                                , new UIClick(request,g, "RequiredSQL"));

                   ui2.AddCell("显示效验脚本", "大于零"
                                , new UIClick(request,g, "ShowSQL"));

                   switch (sub.Type)
                   {
                       case ControlType.Select:

                           ui2.NewSection()
                            .AddCell("选项来源", sub.SelectCommand
                                , new UIClick(request,g, "Command"));

                           break;
                   }
                   UICell cell = UICell.Create("UI", new UMC.Web.WebMeta().Put("text", "删除").Put("Icon", "\uf014").Put("click"
                           , new UIClick(request,g, "Del")));
                   cell.Style.Name("text", new UIStyle().Color(0xf00));
                   ui.NewSection().Add(cell);

                   ui.SendTo(sub.Type == ControlType.List ? "WorkFlow.Control.DelList" : "WorkFlow.Control.Del", this.Context, "WorkFlow.Control");


               });
                switch (Model)
                {
                    case "IsRequired":
                        var IsRequired = this.AsyncDialog("IsRequired", g =>
                        {
                            var dl = new UISelectDialog() { Title = "组件标题" };
                            dl.Options.Put("是", "true", sub.IsRequired == true).Put("否", "false", sub.IsRequired != true);

                            return dl;
                        });
                        DataFactory.Instance().Put(new TaskFormControl
                        {
                            ItemId = sub.ItemId,
                            IsRequired = IsRequired == "true"
                        });
                        break;
                    case "Caption":
                        var title = UIDialog.AsyncDialog(this.Context, "Caption", g =>
                       {
                           var dl = new UIFormDialog() { Title = "组件标题" };
                           dl.AddText("组件标题", "Caption", sub.Caption);
                           dl.Submit("确认更改", "WorkFlow.Control");
                           return dl;
                       });

                        DataFactory.Instance().Put(new TaskFormControl
                        {
                            ItemId = sub.ItemId,
                            Caption = title
                        });
                        break;
                    case "Code":
                        var Code = UIDialog.AsyncDialog(this.Context, "Code", g =>
                        {
                            var dl = new UIFormDialog() { Title = "组件名称" };
                            dl.AddText("组件名称", "Code", sub.Code);
                            dl.Submit("确认更改", "WorkFlow.Control");
                            return dl;
                        });
                        if (sub.Code != Code)
                        {
                            if (DataFactory.Instance().TaskFormControl(sub.TaskId.Value, sub.ForId ?? 0).Any(r => r.Code == Code))
                            {
                                this.Prompt("已经存在此代码");
                            }

                            DataFactory.Instance().Put(new TaskFormControl
                            {
                                ItemId = sub.ItemId,
                                Code = Code ?? String.Empty
                            });
                        }
                        break;
                    case "PlaceHolder":
                        var PlaceHolder = this.AsyncDialog("PlaceHolder", g =>
                       {
                           var dl = new UIFormDialog() { Title = "空值提示" };
                           dl.AddText("空值提示", "PlaceHolder", sub.PlaceHolder).NotRequired();
                           dl.Submit("确认更改", "WorkFlow.Control");
                           return dl;
                       });



                        DataFactory.Instance().Put(new TaskFormControl
                        {
                            ItemId = sub.ItemId,
                            PlaceHolder = PlaceHolder["PlaceHolder"] ?? String.Empty
                        });
                        break;
                    case "Tip":
                        var Tip = this.AsyncDialog("Tip", g =>
                        {
                            var dl = new UIFormDialog() { Title = "分组名称" };
                            dl.AddText("分组名称", "Tip", sub.Tip).NotRequired();//.PlaceHolder("移除分组请用none");
                            dl.Submit("确认更改", "WorkFlow.Control");
                            return dl;
                        });
                        DataFactory.Instance().Put(new TaskFormControl
                        {
                            ItemId = sub.ItemId,
                            Tip = Tip["Tip"] ?? String.Empty
                        });
                        break;
                    case "Command":
                         
                        var Command = this.AsyncDialog("Detail", "WorkFlow", "MappInfo");

                        DataFactory.Instance().Put(new TaskFormControl
                        {
                            ItemId = sub.ItemId,
                            SelectCommand = String.Equals(Command, "none") ? String.Empty : Command
                        });

                        break;
                    case "Detail":

                        var cmd = "";
                        var model = "";
                        var Details = this.AsyncDialog("Detail", g =>
                        {
                            if (String.IsNullOrEmpty(sub.DetailCommand) == false)
                            {
                                var pIndex = sub.DetailCommand.IndexOf('.');
                                if (pIndex > 0)
                                {
                                    model = sub.DetailCommand.Substring(0, pIndex);
                                    cmd = sub.DetailCommand.Substring(pIndex + 1);
                                }
                            }

                                    var dl = new UIFormDialog() { Title = "明细指令" };
                            dl.AddText("模块", "Model", model).NotRequired();
                            dl.AddText("指令", "Command", cmd).NotRequired();//.PlaceHolder("移除分组请用none");
                            dl.Submit("确认更改", "WorkFlow.Control");
                            return dl;
                        });

                        cmd = Details["Command"];
                        model = Details["Model"];

                        if (String.IsNullOrEmpty(model)|| String.IsNullOrEmpty(cmd))
                        {
                            DataFactory.Instance().Put(new TaskFormControl
                            {
                                ItemId = sub.ItemId,
                                DetailCommand =  String.Empty 
                            });
                        }
                        else
                        {

                            DataFactory.Instance().Put(new TaskFormControl
                            {
                                ItemId = sub.ItemId,
                                DetailCommand = $"{model}.{cmd}"
                            });
                        }

                        break;
                    case "CheckSQL":
                        //if(String.IsNullOrEmpty)
                        Check(taskForm);
                        var CheckSQL = this.AsyncDialog("CheckSQL", g =>
                        {
                            var form = new UIFormDialog() { Title = "值检测脚本" };
                            form.AddTextarea("SQL脚本", "CheckSQL", sub.CheckSQL).Put("Rows", 6).NotRequired();
                            form.AddFooter("在编辑状态，检验输入的数据，当第一行，第一列的为字段串，则提示");
                            form.Submit("确认", "WorkFlow.Control");
                            return form;
                        });
                        DataFactory.Instance().Put(new TaskFormControl
                        {
                            ItemId = sub.ItemId,
                            CheckSQL = CheckSQL["CheckSQL"] ?? String.Empty
                        });
                        break;
                    case "ShowSQL":
                        Check(taskForm);
                        var ShowSQL = this.AsyncDialog("ShowSQL", g =>
                        {
                            var form = new UIFormDialog() { Title = "展示效验脚本" };

                            form.AddTextarea("SQL脚本", "ShowSQL", sub.ShowSQL).Put("Rows", 6).NotRequired();
                            form.AddFooter("在编辑状态，且是显示的时候，第一行第一列大于0来则显示");

                            form.Submit("确认", "WorkFlow.Control");


                            return form;
                        });
                        DataFactory.Instance().Put(new TaskFormControl
                        {
                            ItemId = sub.ItemId,
                            ShowSQL = ShowSQL["ShowSQL"] ?? String.Empty
                        });
                        break;
                    case "RequiredSQL":
                        Check(taskForm);
                        var RequiredSQL = this.AsyncDialog("RequiredSQL", g =>
                        {
                            var form = new UIFormDialog() { Title = "空值效验脚本" };
                            form.AddTextarea("SQL脚本", "RequiredSQL", sub.RequiredSQL).Put("Rows", 6).NotRequired();

                            form.AddFooter("在编辑状态，且是必须输入，判断第一行第一列大于0，则必须输入");
                            form.Submit("确认", "WorkFlow.Control");


                            return form;
                        });
                        DataFactory.Instance().Put(new TaskFormControl
                        {
                            ItemId = sub.ItemId,
                            RequiredSQL = RequiredSQL["RequiredSQL"] ?? String.Empty
                        });
                        break;
                    case "ValueSQL":
                        Check(taskForm);
                        var ValueSQL = this.AsyncDialog("ValueSQL", g =>
                        {
                            var form = new UIFormDialog() { Title = "输入处理脚本" };
                            form.AddTextarea("SQL脚本", "ValueSQL", sub.ValueSQL).Put("Rows", 6).NotRequired();

                            form.AddFooter("编辑完成后，值转化脚本，把第一行用字典的形式加入表单");
                            form.Submit("确认", "WorkFlow.Control");


                            return form;
                        });
                        DataFactory.Instance().Put(new TaskFormControl
                        {
                            ItemId = sub.ItemId,
                            ValueSQL = ValueSQL["ValueSQL"] ?? String.Empty
                        });
                        break;
                    case "ValueKey":
                        var ValueKey = this.AsyncDialog("ValueKey", g =>
                        {
                            var dl = new UIFormDialog() { Title = "值字段" };
                            dl.AddText("值字段", "ValueKey", sub.ValueKey).NotRequired();
                            dl.Submit("确认更改", "WorkFlow.Control");
                            return dl;
                        });
                        DataFactory.Instance().Put(new TaskFormControl
                        {
                            ItemId = sub.ItemId,
                            ValueKey = ValueKey["ValueKey"] ?? String.Empty
                        });
                        break;
                    case "Seq":
                        var Seq = Utility.IntParse(UIDialog.AsyncDialog(this.Context, "Seq", g =>
                        {
                            var dl = new UIFormDialog() { Title = "展示顺序" };
                            dl.AddNumber("展示顺序", "Seq", sub.Seq);
                            dl.Submit("确认更改", "WorkFlow.Control");
                            return dl;
                        }), 0);
                        DataFactory.Instance().Put(new TaskFormControl
                        {
                            ItemId = sub.ItemId,
                            Seq = Seq
                        });
                        break;
                    case "Type":
                        var sType = UMC.Data.Utility.Parse(this.AsyncDialog("Type", g =>
                        {
                            var opts = new ListItemCollection().Put("只读", ControlType.Readonly.ToString())
                               .Put("文本", ControlType.Text.ToString())
                               .Put("日期", ControlType.Date.ToString())
                               .Put("选择框", ControlType.Select.ToString())
                               .Put("图片", ControlType.Image.ToString())
                               .Put("图标", ControlType.Icon.ToString())
                               .Put("附件", ControlType.Attachment.ToString());
                            if ((sub.ForId ?? 0) == 0)
                            {
                                opts.Put("列表", ControlType.List.ToString());
                            }
                            var grid = UIDialog.Create(new UIGridDialog.Header("Value", 0).PutField("Text", "名称").PutField("Value", "编码"), opts.ToArray());
                            grid.Title = "组件类型";

                            opts.Put("数字", ControlType.Number.ToString()).Put("扫一扫", ControlType.Scaning.ToString());
                            return grid;
                        }), ControlType.Text);

                        DataFactory.Instance().Put(new TaskFormControl
                        {
                            ItemId = sub.ItemId,
                            Type = sType
                        });
                        break;
                    case "Del":
                        if (sub.Type == ControlType.List)
                        {
                            if (DataFactory.Instance().TaskFormControl(SId, sub.ItemId.Value).Length > 0)
                            {
                                this.Prompt("请先删除子项，再删除列表");
                            }
                            else
                            {
                                DataFactory.Instance().Delete(sub);
                                this.Context.Send("WorkFlow.Control.DelList", false);
                            }
                        }
                        else
                        {
                            DataFactory.Instance().Delete(sub);
                            this.Context.Send("WorkFlow.Control.Del", false);
                        }
                        break;
                }
            }

            this.Context.Send("WorkFlow.Control", true);
        }

    }
}